package com.itheima.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.itheima.entiy.Dish;
import com.itheima.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import java.io.File;
import java.time.LocalDateTime;

@Configuration
public class DeleteImgTask {

    @Value("${reggie.path}")
    private String imgPath;

    @Autowired
    private DishService dishService;

    @Scheduled(cron = "0 0 */1 * * *")
    public void deleteImg(){
        System.out.println("定时任务: "+LocalDateTime.now());
        File file = new File(imgPath);
        File[] files = file.listFiles();
        for (File f : files) {
            if (f.isDirectory()){
                System.out.println("文件夹: "+f.getName());
            }else {
                System.out.println("文件: "+f.getName());
                LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Dish::getImage,f.getName());
                int count = dishService.count(wrapper);
                if (count==0){
                    f.delete();
                }
            }
        }
    }

}